//
//  QuestionViewController.m
//  inquiry
//
//  Created by 高宇 on 2020/5/23.
//  Copyright © 2020 高宇. All rights reserved.
//
#define SCREEN_WIDTH  ([[UIScreen mainScreen] bounds].size.width)
#define SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)

#define kWeakSelf(type) __weak typeof(type) weak##type = type;
#define kStrongSelf(type) __strong typeof(type) type = weak##type;

#import "QuestionnaireDetailVC.h"
#import "DetailCell.h"
#import "BlankCell.h"
#import "GXToast.h"
#import "ULNetHelper.h"
#import "Interface.h"
#import "NSString+MD5.h"
#import "FinishViewController.h"
#import "JsonObject.h"

@interface QuestionnaireDetailVC ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) NSArray *arr;  //总数据
@property (strong, nonatomic) NSMutableArray *linkArr;  //答案数据

@property (strong, nonatomic) NSDictionary *seletedDic;  //当前页面对应的数据
@property (copy, nonatomic) NSString *topTopicIndex;  //上一页面对应topicIndex
@end

static NSString * const reuseIdentifier = @"Cell";
static NSString * const blankCell = @"BlankCell";

@implementation QuestionnaireDetailVC

//在页面出现的时候就将黑线隐藏起来
 -(void)viewWillAppear:(BOOL)animated
{
    //显示导航栏下面的线条
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
        
    [self createUI];
    [self getData];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 40, 30);
    [backButton setTitle:@" 返回" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor colorWithRed:173/255.0 green:173/255.0 blue:189/255.0 alpha:1.0] forState:0];
    [backButton setImage:[[UIImage imageNamed:@"fanhui"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];

    [backButton addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    
    self.linkArr = [NSMutableArray array];  //初始化数组
}

- (void)backClick:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)getData{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *teacherId = [user objectForKey:@"teacherId"];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"questionnaireId"] = self.questionnaireId;
    dic[@"userId"] = teacherId;
    
    NSMutableDictionary *dic2 = [NSMutableDictionary dictionary];
    dic2[@"questionnaireId"] = self.questionnaireId;
    dic2[@"studentId"] = self.studentId;
    dic2[@"teacherId"] = teacherId;
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务1
        dispatch_group_enter(group);   //标志着一个任务追加到 group，执行一次，相当于 group 中未执行完毕任务数+1
        [ULNetHelper POST:queryDetailPath parameters:dic success:^(id responseObject) {
            NSDictionary *dic = responseObject;
            long code = [dic[@"code"] longValue];
            if (code == 200) {
                NSString *title = responseObject[@"data"][@"title"];
                self.title = title;

                self.arr = responseObject[@"data"][@"data"];
            }else{
                NSString *msg = responseObject[@"msg"];
                [GXToast showText:msg];
            }
            dispatch_group_leave(group);
        }];
    });
    
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务2
        dispatch_group_enter(group);
        [ULNetHelper POST:querySolutionPath parameters:dic2 success:^(id responseObject) {
            NSDictionary *dic = responseObject;
            long code = [dic[@"code"] longValue];
            if (code == 200) {
                self.linkArr = [JsonObject objectWithString:responseObject[@"data"]];
                
            }else{
                NSString *msg = responseObject[@"msg"];
                [GXToast showText:msg];
            }
            dispatch_group_leave(group);
        }];
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        // 等前面的异步任务1、任务2都执行完毕后，回到主线程执行下边任务
        NSMutableArray *array = [NSMutableArray array];
        for (int i=0; i<self.linkArr.count; i++) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.linkArr[i]];
            for (int j=0; j<self.arr.count; j++) {
                NSDictionary *tempDic = self.arr[j];
                NSString *topicIndex = [NSString stringWithFormat:@"%@",tempDic[@"topicIndex"]];
                if ([dic[@"topicIndex"] isEqualToString:topicIndex]) {
                    [dic setValue:[JsonObject objectWithString:tempDic[@"topicOption"]] forKey:@"topicOption"];
                    [dic setValue:tempDic[@"subjectType"] forKey:@"subjectType"];
                    [dic setValue:tempDic[@"questionnaireTopic"] forKey:@"questionnaireTopic"];
                    break;
                }
            }
            [array addObject:dic];
        }
        NSLog(@"array == %@",array);
        self.linkArr = array;
        [self.collectionView reloadData];
    });
}

- (BOOL)isPhoneX {
    BOOL iPhoneX = NO;
    if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {//判断是否是手机
        return iPhoneX;
    }
    if (@available(iOS 11.0, *)) {
        UIWindow *mainWindow = [[UIApplication sharedApplication] keyWindow];
        if (mainWindow.safeAreaInsets.bottom > 0.0) {
            iPhoneX = YES;
        }
    }
    return iPhoneX;
}

- (void)createUI{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-44);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    
    self.collectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-44);
    if ([self isPhoneX]) {  //判断刘海屏
        layout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-44-24-34);
        self.collectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-44-24-34);
    }
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.backgroundColor  = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.scrollEnabled = NO;
    
    if (@available(iOS 10.0,*)) {
       self.collectionView.prefetchingEnabled = NO;
    }
    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([DetailCell class]) bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([BlankCell class]) bundle:nil] forCellWithReuseIdentifier:blankCell];
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.linkArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"index == %ld",(long)indexPath.row);
    if (indexPath.row+1 == self.linkArr.count) {
        UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
        [rightButton setTitle:@"完成" forState:0];
        [rightButton setTitleColor:[UIColor whiteColor] forState:0];
        rightButton.backgroundColor = [UIColor colorWithRed:110/255.0 green:132/255.0 blue:238/255.0 alpha:1.0];
        rightButton.layer.cornerRadius = 10;
        [rightButton addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightitem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
        self.navigationItem.rightBarButtonItem = rightitem;
    }
    
    kWeakSelf(self);
    NSDictionary *dic = self.linkArr[indexPath.row];
    NSString *subjectType = dic[@"subjectType"];
    //单选 或 多选
    if ([subjectType isEqualToString:@"select"] || [subjectType isEqualToString:@"select_many"]) {
        DetailCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
        [cell.scrollView setContentOffset:CGPointMake(0,0) animated:NO];
        cell.numberLabel.text = [NSString stringWithFormat:@"%ld/%lu",(long)indexPath.row+1,(unsigned long)self.linkArr.count];
        cell.mianTextView.text = dic[@"questionnaireTopic"];
        if ([subjectType isEqualToString:@"select_many"]) {
            cell.mianTextView.text = [cell.mianTextView.text stringByAppendingString:@"（多选题）"];
        }
        [cell textViewDidChange:cell.mianTextView];
        cell.subjectType = subjectType;
        cell.seletedDic = dic;
        cell.topicOptionArr = dic[@"topicOption"];
        
        
        cell.topBlcok = ^{
            if (indexPath.row != 0) {
                kStrongSelf(self);
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
            }else{
                [GXToast showText:@"已经是第一题啦"];
            }
        };
        cell.nextBlcok = ^{
            if (indexPath.row+1 < self.linkArr.count) {
                kStrongSelf(self);
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row+1 inSection:0] atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
            }else{
                [GXToast showText:@"已经是最后一题啦"];
            }
        };
        return cell;
    }
    
    //填空
    else if ([subjectType isEqualToString:@"fill_blank"]) {
        BlankCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:blankCell forIndexPath:indexPath];
        cell.numberLabel.text = [NSString stringWithFormat:@"%ld/%lu",(long)indexPath.row+1,(unsigned long)self.arr.count];
        cell.mianTextView.text = dic[@"questionnaireTopic"];
        cell.textView.text = dic[@"topicOption"];
        cell.topBlcok = ^(NSDictionary * _Nonnull lastDic) {
            if (indexPath.row != 0) {
                kStrongSelf(self);
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
            }else{
                [GXToast showText:@"已经是第一题啦"];
            }
        };
        cell.nextBlcok = ^(NSDictionary * _Nonnull dataDic) {
            if (indexPath.row+1 < self.linkArr.count) {
                kStrongSelf(self);
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row+1 inSection:0] atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
            }else{
                [GXToast showText:@"已经是最后一题啦"];
            }
        };
        return cell;
    }
    else{
        //错误情况处理
        DetailCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
        return cell;
    }
}


@end
